package com.breakfast.fun.ui.user.cart;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.adapter.user.CartProductAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.dao.Address;
import com.breakfast.fun.dao.AddressDao;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.home.cart.SubmitOrder;
import com.breakfast.fun.data.entity.home.cart.SubmitOrderItem;
import com.breakfast.fun.data.entity.home.product.WeekdayState;
import com.breakfast.fun.data.entity.user.address.AddressData;
import com.breakfast.fun.data.entity.user.coupon.Coupon;
import com.breakfast.fun.data.entity.user.recharge.PayBean;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.ui.user.address.UserAddressActivity;
import com.breakfast.fun.ui.user.coupon.CouponActivity;
import com.breakfast.fun.ui.user.pay.BFPayActivity;
import com.breakfast.fun.util.JumpUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.PopUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.util.TimeUtil;
import com.breakfast.fun.view.widget.CustomDialog;
import com.breakfast.fun.view.widget.TitleBarView;
import com.breakfast.fun.view.widget.WheelPicker;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.breakfast.fun.util.DaoUtil.getProductList;

public class UserCartActivity extends BaseActivity<UserCartPresenter, UserCartModel> implements UserCartContract.View {


    @Bind(R.id.tbv_user_cart)
    TitleBarView mTbvUserCart;
    @Bind(R.id.lv_cart_product)
    ListView mLvCartProduct;
    @Bind(R.id.ll_cart_product)
    LinearLayout mLlCartProduct;
    @Bind(R.id.iv_cart_empty)
    ImageView mIvCartEmpty;
    @Bind(R.id.tv_cart_count)
    TextView mTvCartCount;
    @Bind(R.id.rl_cart_count)
    RelativeLayout mRlCartCount;
    @Bind(R.id.tv_cart_bottom_total)
    TextView mTvCartBottomTotal;
    @Bind(R.id.tv_cart_price)
    TextView mTvCartPrice;
    @Bind(R.id.btn_cart_submit)
    Button mBtnCartSubmit;
    @Bind(R.id.rl_cart_bottom)
    RelativeLayout mRlCartBottom;
    @Bind(R.id.rl_user_cart)
    RelativeLayout mRlUserCart;


    private View mHeaderView;

    private CartProductAdapter adapter;

    private ProductCartDao mProductCartDao;
    private AddressDao mAddressDao;

    private ViewHolder holder;

    private CustomDialog mDialog;

    private String mSendTime;
    private List<String> sendTimeList = new ArrayList<>();
    private List<WeekdayState> weekDayList = new ArrayList<>();
    private List<String> canBuyDayList = new ArrayList<>();

    private String firstCanBuyDay = "";
    Coupon.CouponData curCoupon;
    private List<Coupon.CouponData> mCouponDataList = new ArrayList<>();
    AddressData curAddress;
    private final static int COUPONREQUEST = 1;
    private final static int NOCOUPON = 2;
    private final static int YESCOUPON = 3;

    private float curValue = 0;

    private Boolean isNoCoupon = true;

    private Boolean isFromMall = false;
    private double curTotalPrice = 0;           //当前购物车总金额（不含优惠券）
    private CustomDialog dialog;
    private int curCondition = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_cart;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);

        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
        mAddressDao = DaoMaster.newDevSession(context, "zaofan.db").getAddressDao();

        mTbvUserCart.setAll("购物车");
        mTbvUserCart.setRightImg(R.drawable.ic_recover);
        mTbvUserCart.setBack(this);
        mTbvUserCart.setRightListener(v -> {
            recoverProduct();
        });

        mHeaderView = LayoutInflater.from(this).inflate(R.layout.layout_user_cart_head, null);
        holder = new ViewHolder(mHeaderView);

        mLvCartProduct.addHeaderView(mHeaderView);

        holder.mRlCartAddress.setOnClickListener(v -> {
            if (Constant.getUserData() == null) {
                T.show("请登录");
                JumpUtil.toLogin(context);
                return;
            }
            Intent intent = new Intent(UserCartActivity.this, UserAddressActivity.class);
            intent.putExtra("isFromCart", true);
            if (curAddress != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("chooseAddress", curAddress);
                intent.putExtras(bundle);
            }
            startActivity(intent);
        });

        holder.mRlCartNoAddress.setOnClickListener(v -> {
            if (Constant.getUserData() == null) {
                T.show("请登录");
                JumpUtil.toLogin(context);
                return;
            }
            Intent intent = new Intent(UserCartActivity.this, UserAddressActivity.class);
            intent.putExtra("isFromCart", true);

            startActivity(intent);
        });

        Address address = mAddressDao.loadByRowId(1);
        if (address != null) {
            holder.mTvCartMobile.setText(address.getMobile());
            holder.mTvCartName.setText(address.getName());
            holder.mTvCartAddress.setText(address.getAddress());
            holder.mRlCartAddress.setVisibility(View.VISIBLE);
            holder.mRlCartNoAddress.setVisibility(View.GONE);
            curAddress = new AddressData();
            curAddress.setId(address.getAddressId());
            curAddress.setMobile(address.getMobile());
            curAddress.setAddress(address.getAddress());
            curAddress.setConsignee(address.getName());

        } else {
            holder.mRlCartNoAddress.setVisibility(View.VISIBLE);
            holder.mRlCartAddress.setVisibility(View.GONE);
        }

        holder.mTvCartSendTime.setOnClickListener(v -> {
            presenter.getSendTime();
        });

        mBtnCartSubmit.setOnClickListener(v -> {
            if (holder.mRlCartAddress.getVisibility() != View.VISIBLE) {
                T.show("请先添加地址");
                return;
            }
            if (adapter.getCount() == 0) {
                T.show("购物车为空,请添加商品");
                return;
            }
            if (holder.mTvCartSendTime.getText().toString().equals("请选择送达时间")) {
                T.show("请选择送达时间");
                return;
            }
            dialog = new CustomDialog(UserCartActivity.this, R.style.dialog_style,
                    R.layout.dialog_custom, "确认提示", "是否已选完早餐前往结算？", false, false, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    submitOrder();
                }
            });
            dialog.show();
        });

        //点击优惠券弹出优惠券列表
        holder.mRlCartCoupon.setOnClickListener(v -> {
            if (Constant.getUserData() == null) {
                T.show("请登录");
                JumpUtil.toLogin(context);
                return;
            }
            Intent intent = new Intent(UserCartActivity.this, CouponActivity.class);
            intent.putExtra("totalPrice", curTotalPrice);
            if (curCoupon != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("chooseCoupon", curCoupon);
                intent.putExtras(bundle);
            }
            startActivityForResult(intent, COUPONREQUEST);
        });

    }

    //选择优惠券回传
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == COUPONREQUEST && resultCode == NOCOUPON) {
            isNoCoupon = true;
            curCoupon = null;
            holder.mTvCartCoupon.setText("不使用优惠券");
            curValue = 0;
        }

        if (requestCode == COUPONREQUEST && resultCode == YESCOUPON) {
            isNoCoupon = false;
            curCoupon = (Coupon.CouponData) data.getExtras().getSerializable("coupon");
            holder.mTvCartCoupon.setText(curCoupon.getName());
            curValue = curCoupon.getValue();
        }

        mTvCartPrice.setText(String.format("%.2f", curTotalPrice - curValue));
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void submitOrder() {
        if (Constant.getUserData() == null) {
            T.show("请登录");
            JumpUtil.toLogin(context);
            return;
        }
        SubmitOrder submitOrder = new SubmitOrder();
        submitOrder.setAddress(mAddressDao.loadByRowId(1).getAddressId());
        submitOrder.setMark(holder.mEtCartMark.getText().toString());
        submitOrder.setUserId(Constant.getUserData().getId());
        submitOrder.setTime(holder.mTvCartSendTime.getText().toString());
        submitOrder.setMobile(Constant.getUserData().getMobile());

        Map<String, List<SubmitOrderItem>> map = new HashMap<>();
        List<SubmitOrderItem> listItem = new ArrayList<>();
        SubmitOrderItem item;

        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();

        List<ProductCart> productCarts = mProductCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            item = new SubmitOrderItem();
            ProductCart productCart = productCarts.get(i);
            item.setGoodAccount(productCart.getNum());
            item.setGoodId(productCart.getProductId());
            item.setGoodImage(productCart.getImage());
            item.setGoodName(productCart.getName());
            item.setDate(productCart.getDate());
            item.setProductClassId(productCart.getProductClassId());
            item.setCategoryId(productCart.getCategoryId());
            listItem.add(item);
        }

        for (int i = 0; i < listItem.size(); i++) {
            List<SubmitOrderItem> submitOrderItem = new ArrayList<>();
            submitOrderItem.add(listItem.get(i));
            map.put(listItem.get(i).getGoodId() + "," + listItem.get(i).getDate(), submitOrderItem);
        }

        submitOrder.setShopData(map);


        //使用优惠券的逻辑
        if (!isNoCoupon) {
            submitOrder.setCouponId(curCoupon.getCouponId());
            submitOrder.setCouponUserId((long) curCoupon.getId());
            submitOrder.setTotalPrice(curTotalPrice + "");
        }

        String order = new Gson().toJson(submitOrder);
        L.d(order);
        presenter.submitOrder(order);
    }

    /**
     * 送达时段弹窗设置
     */
    @Override
    public void showPopTime() {
        View contentView = LayoutInflater.from(context).inflate(R.layout.widget_pop_picker, null);

        TextView tvWheelpickerCancel = (TextView) contentView.findViewById(R.id.tv_wheelpicker_cancel);
        TextView tvWheelpickerOk = (TextView) contentView.findViewById(R.id.tv_wheelpicker_ok);
        final WheelPicker wpWheelPicker = (WheelPicker) contentView.findViewById(R.id.wp_wheelpicker);
        wpWheelPicker.setData(sendTimeList);
        final PopupWindow popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        PopUtil.setPop(popupWindow);

        popupWindow.showAtLocation(mLlCartProduct, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        backgroundAlpha(0.5f);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

        tvWheelpickerOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String sendTime = (String) wpWheelPicker.getData().get(wpWheelPicker.getCurrentItemPosition());
                holder.mTvCartSendTime.setText(sendTime);
                mSendTime = sendTime;
                popupWindow.dismiss();
            }
        });

        tvWheelpickerCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void setSendTime(List<String> data) {
        sendTimeList = data;
        showPopTime();
    }


    @Override
    public void setSendDate(List<WeekdayState> weekdayStates) {

        for (WeekdayState state : weekdayStates) {
            if (state.getState().equals("2")) {
                firstCanBuyDay = state.getWdate();
            }
            if (!state.getState().equals("1")) {
                String date = state.getWdate() + " [" + TimeUtil.CalcuDate(state.getWdate()) + "]";
                canBuyDayList.add(date);
            }
        }

        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
        List<ProductCart> productCarts = mProductCartDao.loadAll();
        List<ProductCart> productCarts1 = new ArrayList<>();
        for (ProductCart cart : productCarts) {
            for (WeekdayState state : weekdayStates) {
                if (cart.getDate().equals(state.getWdate())) {
                    if (state.getState().equals("1")) {
                        productCarts1 = getProductList(cart.getCategoryId(), cart.getProductId(), firstCanBuyDay);
                        if (productCarts1 != null && productCarts1.size() == 1) {
                            productCarts.remove(cart);
                            mProductCartDao.delete(cart);
                            productCarts1.get(0).setNum(productCarts1.get(0).getNum() + 1);
                        }
                        cart.setDate(firstCanBuyDay);
                    }
                }
            }
        }

        mProductCartDao.updateInTx(productCarts);
        if (productCarts1.size() == 1) {
            mProductCartDao.updateInTx(productCarts1);
        }

        adapter = new CartProductAdapter(context, mProductCartDao.loadAll(), canBuyDayList);
        mLvCartProduct.setAdapter(adapter);
//        adapter.setAddClickListener(new CartProductAdapter.addClickListener() {
//            @Override
//            public void add(View view) {
//                mCartAnimUtil.setFromView(view);
//                mCartAnimUtil.setToView(mRlCartCount);
//                mCartAnimUtil.setRootView(mRlUserCart);
//                mCartAnimUtil.startAnim();
//            }
//        });

        if (mProductCartDao.loadAll().size() == 0) {
            mLvCartProduct.setVisibility(View.GONE);
            mIvCartEmpty.setVisibility(View.VISIBLE);
        } else {
            mLvCartProduct.setVisibility(View.VISIBLE);
            mIvCartEmpty.setVisibility(View.GONE);
        }
    }

    @Override
    public void showOrderInfo(PayBean data) {
        T.show("订单提交成功");
        mProductCartDao.deleteAll();
        Intent intent = new Intent(this, BFPayActivity.class);
        intent.putExtra("payBean", data);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void setCoupon(Coupon coupon) {
        mCouponDataList.clear();
        mCouponDataList.addAll(coupon.getData());
        autoChooseCoupon(mCouponDataList, true);
    }

    private void recoverProduct() {
        mDialog = new CustomDialog(UserCartActivity.this, R.style.dialog_style,
                R.layout.dialog_custom, "提示", "确定要清空购物车吗？", false, false, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
                mProductCartDao.deleteAll();
                mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
                adapter = new CartProductAdapter(context, mProductCartDao.loadAll(), canBuyDayList);
                mLvCartProduct.setAdapter(adapter);
//                adapter.setAddClickListener(new CartProductAdapter.addClickListener() {
//                    @Override
//                    public void add(View view) {
//                        mCartAnimUtil.setFromView(view);
//                        mCartAnimUtil.setToView(mRlCartCount);
//                        mCartAnimUtil.setRootView(mRlUserCart);
//                        mCartAnimUtil.startAnim();
//                    }
//                });
                if (mProductCartDao.loadAll().size() == 0) {
                    mLvCartProduct.setVisibility(View.GONE);
                    mIvCartEmpty.setVisibility(View.VISIBLE);
                } else {
                    mLvCartProduct.setVisibility(View.VISIBLE);
                    mIvCartEmpty.setVisibility(View.GONE);
                }
            }
        });
        mDialog.show();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CartEvent event) {
        curTotalPrice = event.getTotalPrice();
        if (event.getTotalNum() > 0) {
            mTvCartCount.setVisibility(View.VISIBLE);
        } else {
            mTvCartCount.setVisibility(View.GONE);
        }
        mTvCartCount.setText(event.getTotalNum() + "");
        if (event.getTotalPrice() < 0) {
            event.setTotalPrice(0);
        }
        autoChooseCoupon(mCouponDataList, false);
        if (curCoupon != null) {
            if (event.getTotalPrice() < curCoupon.getConditions().doubleValue()) {
                holder.mTvCartCoupon.setText("未选择优惠券");
                isNoCoupon = true;
                curCoupon = null;
                curValue = 0;
            }
        }
        if (curCoupon != null) {
            mTvCartPrice.setText(String.format("%.2f", event.getTotalPrice() - curCoupon.getValue()));
        } else {
            mTvCartPrice.setText(String.format("%.2f", event.getTotalPrice()));
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventAddress(AddressData event) {
        Address address = new Address();
        address.setId((long) 1);
        address.setMobile(event.getPhone());
        address.setAddress(event.getAddress());
        address.setName(event.getConsignee());
        address.setAddressId(event.getId());
        mAddressDao.insertOrReplace(address);

        holder.mRlCartNoAddress.setVisibility(View.GONE);
        holder.mRlCartAddress.setVisibility(View.VISIBLE);
        holder.mTvCartMobile.setText(address.getMobile());
        holder.mTvCartName.setText(address.getName());
        holder.mTvCartAddress.setText(address.getAddress());

        //保存当前选中的地址
        curAddress = event;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventDatePop(PopupWindow event) {
        event.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

        backgroundAlpha(0.5f);

        event.showAtLocation(mLlCartProduct, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void autoChooseCoupon(List<Coupon.CouponData> coupon, boolean isNeedSetPrice) {
        curValue = 0;
        if (coupon != null && coupon.size() != 0) {
            for (Coupon.CouponData c : coupon
                    ) {
                if (curTotalPrice >= c.getConditions().doubleValue() && c.getValue() >= curValue) {

                    //每次价格变化判断当前最大的优惠券
                    curCondition = c.getConditions().intValue();
                    curValue = c.getValue();
                    curCoupon = c;
                }
            }
        }
        //有符合条件的优惠券
        if (curCoupon != null) {
            holder.mTvCartCoupon.setText("自动选择" + curCoupon.getName());
            if (isNeedSetPrice) {
                mTvCartPrice.setText(String.format("%.2f", curTotalPrice - curCoupon.getValue()));
            }
            isNoCoupon = false;
        }
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }


    static class ViewHolder {
        @Bind(R.id.tv_cart_name)
        TextView mTvCartName;
        @Bind(R.id.tv_cart_mobile)
        TextView mTvCartMobile;
        @Bind(R.id.tv_cart_address)
        TextView mTvCartAddress;
        @Bind(R.id.ll_cart_head_address)
        LinearLayout mLlCartHeadAddress;
        @Bind(R.id.rl_cart_address)
        RelativeLayout mRlCartAddress;
        @Bind(R.id.rl_cart_no_address)
        RelativeLayout mRlCartNoAddress;
        @Bind(R.id.tv_cart_send_time_left)
        TextView mTvCartSendTimeLeft;
        @Bind(R.id.tv_cart_send_time)
        TextView mTvCartSendTime;
        @Bind(R.id.rl_cart_send_time)
        RelativeLayout mRlCartSendTime;
        @Bind(R.id.ll_cart_time)
        LinearLayout mLlCartTime;
        @Bind(R.id.tv_cart_coupon)
        TextView mTvCartCoupon;
        @Bind(R.id.iv_cart_coupon)
        ImageView mIvCartCoupon;
        @Bind(R.id.rl_cart_coupon)
        RelativeLayout mRlCartCoupon;
        @Bind(R.id.et_cart_mark)
        EditText mEtCartMark;
        @Bind(R.id.ll_cart_head)
        LinearLayout mLlCartHead;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
